import os
import traceback

from git.repo import Repo
from git.repo.fun import is_git_dir
from urllib.parse import quote
import logging
logger = logging.getLogger("GitRepository")
logging.basicConfig(level=logging.DEBUG,
                    filemode='a',
                    format='%(asctime)s [%(levelname)-5s] %(threadName)13s (%(module)s:%(funcName)s:%(lineno)d) - %(message)s'
                    )


class GitRepository(object):
    """
    git仓库管理
    """
    def __init__(self, local_path, repo_url, branch='master'):
        self.local_path = local_path
        self.repo_url = repo_url
        self.repo = None
        self.username = "devspace-admin"
        self.password = "devspace-admin"
        self.initial(repo_url, branch)


    def initial(self, repo_url, branch):
        """
        初始化git仓库
        :param repo_url:
        :param branch:
        :return:
        """
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)
        else:
            os.rmdir(self.local_path)
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            url = self.get_auth_url(repo_url)
            self.repo = Repo.clone_from(url, to_path=self.local_path, branch=branch)
            origin = self.repo.remote()
            old_url = next(origin.urls)
            print("old_url", old_url)
            print("repo_url", repo_url)
            origin.set_url(repo_url, url)
        else:
            self.repo = Repo(self.local_path)

    def get_auth_url(self, repo_url):
        if repo_url.startswith('http://'):
            url = 'http://' + self.username + ':' + self.password + '@' + repo_url[7:]
        elif repo_url.startswith('https://'):
            url = 'https://' + self.username + ':' + self.password + '@' + repo_url[8:]
        else:
            raise Exception('not support url for ' + repo_url)
        return url

    def pull(self, token):
        """
        从线上拉最新代码
        :return:
        """
        try:
            origin = self.repo.remote()
            new_url = self._get_author_url(self.repo_url, token)
            origin.set_url(new_url, self.repo_url)
            self.repo.git.pull()
        except Exception:
            logger.error(traceback.format_exc())
            return False
        finally:
            # 需要把鉴权的url地址换回来
            origin.set_url(self.repo_url, new_url)


    def branches(self):
        """
        获取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
        获取所有提交记录
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def tags(self):
        """
        获取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切换分支
        :param branch:
        :return:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)

    def _get_author_url(self, url, token):
        token = quote(token)
        if url.startswith('http://'):
            new_url = 'http://oauth2:' + token + '@' + url[7:]
        elif url.startswith('https://'):
            new_url = 'https://oauth2:' + token + '@' + url[8:]
        else:
            return None
        return new_url


    def push(self,token):
        """
        提交代码
        """
        try:
            origin = self.repo.remote()
            new_url = self._get_author_url(self.repo_url, token)
            origin.set_url(new_url, self.repo_url)
            rg = self.repo.git
            rg.add("--all")
            rg.commit("-m auto update")
            rg.push()
            return True
        except Exception as e:
            logger.error(traceback.format_exc())
            return False
        finally:
            # 需要把鉴权的url地址换回来
            origin.set_url(self.repo_url, new_url)

    def merge_master(self, branch_name, token):
        try:
            origin = self.repo.remote()
            # old_url = next(origin.urls)
            new_url = self._get_author_url(self.repo_url, token)
            origin.set_url(new_url, self.repo_url)
            # 合入master
            rg = self.repo.git
            rg.merge(branch_name)
            # rg.add("--all")
            # rg.commit("-m merge master")
            rg.push()
            return True
        except Exception as e:
            logger.error(traceback.format_exc())
            return False
        finally:
            # 需要把鉴权的url地址换回来
            origin.set_url(self.repo_url, new_url)


if __name__ == '__main__':
    # local_path = os.path.join('codes', 'luffycity')
    # repo = GitRepository(local_path,remote_path)
    # branch_list = repo.branches()
    # print(branch_list)
    # repo.change_to_branch('dev')
    # repo.pull()
    pass